﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using CQIE.TES.IDAL;
using CQIE.TES.Model;
using Newtonsoft.Json.Linq;

namespace CQIE.TES.DAL
{
    public class StudentDAL : DALBase<Student>, IStudentDAL
    {
        public void Test()
        {

        }
        /// <summary>
        /// 分页、查询
        /// </summary>
        /// <param name="pageNum">分数</param>
        /// <param name="pageSize">每一页有几行</param>
        /// <param name="search">查询关键字</param>
        /// <param name="count">查询总数</param>
        /// <returns></returns>
        public List<Student> GetStudentsPage(int pageNum, int pageSize, string search, out int count)
        {
            using (MyDB db = new MyDB())
            {
                //获取学生总数
                count = db.Student.Where(student => student.Name.Contains(search)).Count();
                // 模糊查询 Contains()
                // Skip():是跳过前n个结果，返回剩余的结果
                // Take():作用是从查询结果中提取前n个结果
                var query = (from s in db.Student
                             where s.Name.Contains(search)
                             orderby s.ID  //必须使用排序才能使用Skip（）,Take()方法
                             select s).Skip(pageNum * pageSize).Take(pageSize).ToList();

                //循环操作查询集合，返回一个学生集合
                return query.Select(stu => new Student()
                {
                    ID = stu.ID,
                    StudentNumber = stu.StudentNumber,
                    Name = stu.Name,
                    IsFreeze = stu.IsFreeze,
                    ClassID = stu.ClassID,
                    ClassCode = stu.Class_.ClassCode,
                    Sex = stu.Sex
                }).ToList();
            }

        }
        /// <summary>
        /// 删除学生（逻辑删除改变IsFreeze的值）
        /// </summary>
        /// <param name="id">通过传入的id找到学生</param>
        public bool DeleteStudent(int id)
        {
            using (MyDB db = new MyDB())
            {
                try
                {
                    var model = db.Student.Find(id);
                    //禁用学生
                    model.IsFreeze = !model.IsFreeze;
                    //IsFreeze修改保存到数据库
                    db.SaveChanges();
                    return true;
                }
                catch
                {
                    return false;
                }


            }
        }


        /// <summary>
        /// 查询学生,该接口暂时禁用（分页方法已经实现按照姓名查询）
        /// </summary>
        /// <param name="nameSearch">根据传入姓名参数查询学生信息</param>
        /// <returns></returns>
        [Obsolete]
        public List<Student> SearchStudent(string nameSearch)
        {
            using (MyDB db = new MyDB())
            {
                //根据姓名模糊查询学生信息
                var queryStudent = (from s in db.Student
                                    where s.Name.Contains(nameSearch)
                                    select s).ToList();
                return queryStudent;
            }
        }
        /// <summary>
        /// 添加（跟新）学生信息
        /// </summary>
        /// <param name="id">获取学生信息的参数</param>
        /// <param name="data">提交表单的数据</param>
        /// <returns></returns>
        public void UpdateStudent([FromBody] JObject data)
        {
            using (MyDB db = new MyDB())
            {
                //根据id获取需要更新的学生
                //var student = db.Student.Find(id);
                //更新学生信息
                db.Student.Add(new Student()
                {
                    
                    ClassID = (int)data["classCode"],
                    IsFreeze = false,
                    Name = (string)data["studentName"],
                    StudentNumber = (string)data["studentNumber"],
                    Sex = (int)data["sex"],
                    PassWord = "123456",
                    
            });
                //student.ClassID = (int?)data["ClassID"];
                //student.ClassCode = (string)data["Class_Name"];
                //student.ID = (int)data["ID"];
                //student.IsFreeze = (bool?)data["IsFreeze"];
                //student.Name = (string)data["Name"];
                //student.StudentNumber = (string)data["StudentNumber"];
                //student.Sex = (int)data["Sex"];
                //更新数据库
                db.SaveChanges();

                ////重新获取更新之后的学生信息
                //var reStudent = db.Student.Find(id);

                ////返回学生信息
                //return new
                //{
                //    //id = reStudent.ID,
                //    studentName = reStudent.Name,
                //    studentNumber = reStudent.StudentNumber,
                //    classID = reStudent.ClassID,
                //    //class_Name = reStudent.ClassCode,
                //    state = reStudent.IsFreeze,
                //    sex = reStudent.Sex
                //};
            }
        }
        /// <summary>
        /// 重置学生密码
        /// </summary>
        /// <param name="id">指定需要重置的学生</param>
        /// <returns></returns>
        public bool ResetPassWord(int id)
        {
            try
            {
                //定义上下文
                using (MyDB db = new MyDB())
                {
                    //根据id查询一条学生信息
                    var model = db.Student.Find(id);
                    //重新设置学生密码为123456
                    model.PassWord = "123456";
                    //更新数据库
                    db.SaveChanges();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 编辑学生
        /// </summary>
        /// <param name="id">通过id找到学生</param>
        /// <param name="data">前端返回的json格式的数据</param>
        /// <returns></returns>
        public bool EditStudent(int id, string studentName, int sex, bool isFreeze, string studentNumber, string passWord, int classID)
        {
            try
            {
                //引用上下文
                using (MyDB db = new MyDB()) {
                    //找到编辑的学生
                    var model = db.Student.Find(id);
                    //更改编辑数据
                    model.StudentNumber = studentNumber;
                    model.Name = studentName;
                    model.Sex = sex;
                    model.ClassID = classID;
                    model.IsFreeze = isFreeze;
                    model.PassWord = passWord;
                    //把数更新到数据库
                    db.SaveChanges();
                }
                return true;
            }
            catch
            {

                return false;
            }

        }

        public Student Login(string username, string password)
        {
            using (MyDB db = new MyDB())
            {
                var model = db.Student.FirstOrDefault(s => s.StudentNumber == username && s.PassWord == password);

                return model;
            }
        }

        public Student Get(int sid)
        {
            using (MyDB db = new MyDB())
            {
                return db.Student.Find(sid);
            }
        }
    }
}
